package com.spark.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.common.core.Result;
import com.spark.common.core.entity.system.SysUser;
import com.spark.common.utils.SecurityUtils;
import com.spark.modules.system.entity.SysUserRole;
import com.spark.modules.system.mapper.SysUserMapper;
import com.spark.modules.system.mapper.SysUserRoleMapper;
import com.spark.modules.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 系统用户Service
 *
 * @author LYCHEE
 * @date 2025/02/18 09:12
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 通过用户名查询用户
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public SysUser getUserByUsername(String username) {
        return baseMapper.getUserByUsername(username);
    }

    /**
     * 新增
     *
     * @param user 系统用户对象
     * @return 成功或失败
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Result<?> add(SysUser user) {
        SysUser datasource = baseMapper.getUserByUsername(user.getUsername());
        if (null != datasource) {
            return Result.fail("账号已存在!");
        }
        String encryptedPassword = SecurityUtils.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        int insert = baseMapper.insert(user);
        if (insert > 0) {
            // 设置角色
            if (StringUtils.isNotEmpty(user.getRoleIds())) {
                setUserRoles(user,false);
            }
        }
        return Result.flag(insert);
    }

    /**
     * 编辑
     *
     * @param sysUser 系统用户对象
     * @return 成功或失败
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Result<?> edit(SysUser sysUser) {
        setUserRoles(sysUser, true);
        int i = baseMapper.updateById(sysUser);
        return Result.flag(i);
    }

    /**
     * 通过ID查询
     *
     * @param id 主键
     * @return 系统用户对象
     */
    @Override
    public Result<?> queryById(String id) {
        SysUser sysUser = baseMapper.selectById(id);
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
        queryWrapper.eq("user_id",sysUser.getId());
        List<SysUserRole> list = sysUserRoleMapper.selectList(queryWrapper);
        List<String> collect = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        sysUser.setRoleIds(String.join(",", collect));
        return Result.ok(sysUser);
    }

    /**
     * 重置密码为：spark@123
     *
     * @return 成功或失败
     */
    @Override
    public Result<?> resetPassWord() {
        String userId = SecurityUtils.getUserId();
        SysUser sysUser = baseMapper.selectById(userId);
        if (Objects.isNull(sysUser)) {
            return Result.fail("用户信息异常");
        }
        String encryptPassword = SecurityUtils.encryptPassword("spark@123");
        sysUser.setPassword(encryptPassword);
        int i = baseMapper.updateById(sysUser);
        return Result.flag(i, "密码重置成功", " 密码重置失败");
    }

    /**
     * 设置用户的角色
     *
     * @param user 用户信息
     * @param clear 是否删除用户角色对应关系
     */
    public void setUserRoles(SysUser user, boolean clear) {
        if (clear){
            sysUserRoleMapper.clear(user.getId());
        }
        String[] split = user.getRoleIds().split(",");
        for (String roleId : split) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            sysUserRoleMapper.insert(userRole);
        }
    }
}
